﻿using System;
using NAudio.Wave;

namespace PT.UI.Windows.Audio {
    public class ToneGenerator : WaveProvider32 {
        
        int sample;
        int sampleToneEnd;
        bool toneOn;

        const float MaxAmplitude = 0.25f;  // let's not hurt our ears  

        public ToneGenerator()
        {
            Frequency = 1000;
        }

        public static ToneGenerator CreateQuarterNoteToneGenerator() {
            return new ToneGenerator { Frequency = 4082 /* C8 */ };
        }

        public float Frequency { get; set; }
        public float Amplitude { 
            get {
                if (toneOn && sampleToneEnd < sample) {
                    toneOn = false;
                }

                return toneOn ? MaxAmplitude : 0f;
            } 
        }

        public void GenerateTone(int durationMilliseconds) {
            int sampleRate = WaveFormat.SampleRate;
            var durationSamples = sampleRate * durationMilliseconds / 1000;
            sampleToneEnd = (sample + durationSamples) % sampleRate;
            toneOn = true;
        }

        public override int Read(float[] buffer, int offset, int sampleCount) {
            int sampleRate = WaveFormat.SampleRate;
            for (int n = 0; n < sampleCount; n++) {
                buffer[n+offset] = (float)(Amplitude * Math.Sin((2 * Math.PI * sample * Frequency) / sampleRate));
                sample++;
                if (sample >= sampleRate) sample = 0;
            }
            return sampleCount;
        }

    }
}
